package com.navinfo.collect.library.map;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.navinfo.collect.library.R;
import com.navinfo.collect.library.map.layers.NIPolygonLayer;
import com.navinfo.collect.library.map.source.NavinfoMapRastorTileSource;
import com.navinfo.collect.library.map.source.NavinfoMultiMapFileTileSource;

import org.oscim.android.canvas.AndroidBitmap;
import org.oscim.layers.Layer;
import org.oscim.layers.LocationLayer;
import org.oscim.layers.marker.ItemizedLayer;
import org.oscim.layers.marker.MarkerInterface;
import org.oscim.layers.marker.MarkerSymbol;
import org.oscim.layers.tile.bitmap.BitmapTileLayer;
import org.oscim.layers.tile.vector.VectorTileLayer;
import org.oscim.map.Map;
import org.oscim.tiling.source.OkHttpEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Cache;
import okhttp3.OkHttpClient;

public class NILayerManager implements ItemizedLayer.OnItemGestureListener {
    private Map vtmMap;
    public static String defaultDir = Environment.getExternalStorageDirectory() + "/" + "NavinfoCollect";
    private String defaultLocalMapPath = defaultDir + "/maps/";
    //图层管理
    private java.util.Map<String, Layer> layersMap = new HashMap<String, Layer>();
    //默认marker图层
    private ItemizedLayer mDefaultMarkerLayer;
    //定位图层
    private LocationLayer mLocationLayer;

    //新增面数据
    private NIPolygonLayer mPolygonLayer;


    public NILayerManager(Context context, Map vtmMap) {
        this.vtmMap = vtmMap;

        //新增marker图标样式
        AndroidBitmap mDefaultBitmap =
                new AndroidBitmap(BitmapFactory.decodeResource(context.getResources(), R.mipmap.marker));
        MarkerSymbol markerSymbol = new MarkerSymbol(mDefaultBitmap, MarkerSymbol.HotspotPlace.BOTTOM_CENTER);
        //新增marker图层
        mDefaultMarkerLayer = new ItemizedLayer(
                vtmMap,
                new ArrayList<MarkerInterface>(),
                markerSymbol,
                this
        );
        addLayer("defaultMarkerLayer", mDefaultMarkerLayer, NIMapView.LAYER_GROUPS.VECTOR.ordinal());

        //定位图层
        mLocationLayer = new LocationLayer(vtmMap);
        addLayer("locationLayer", mLocationLayer, NIMapView.LAYER_GROUPS.ALLWAYS_SHOW_GROUP.ordinal());
    }

    public Layer getRasterTileLayer(Context mContext, String url, String tilePath, boolean useCache) {
        if (this.vtmMap == null) {
            throw new IllegalStateException("无法获取到map对象");
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        NavinfoMapRastorTileSource mTileSource = NavinfoMapRastorTileSource.builder(url).tilePath(tilePath).httpFactory(new OkHttpEngine.OkHttpFactory(builder)).build();
        // 如果使用缓存
        if (useCache) {
            File cacheDirectory = new File(defaultDir, "tiles-raster");
            int cacheSize = 300 * 1024 * 1024; // 300 MB
            Cache cache = new Cache(cacheDirectory, cacheSize);
            builder.cache(cache);
        }

//        mTileSource.setHttpEngine(new OkHttpEngine.OkHttpFactory(builder));
//        mTileSource.setHttpRequestHeaders(Collections.singletonMap("User-Agent", "vtm-android-example"));
//        mTileSource.setCache(new TileCache(mContext, defaultDir, url.substring(url.indexOf(":")+1)));

        BitmapTileLayer rasterLayer = new BitmapTileLayer(this.vtmMap, mTileSource);
        return rasterLayer;
    }

    // 初始化请求在线底图数据
    public Layer getDefaultVectorLayer(boolean useCache) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (useCache) {
            // Cache the tiles into file system
            File cacheDirectory = new File(defaultDir, "tiles-vector");
            int cacheSize = 200 * 1024 * 1024; // 200 MB
            Cache cache = new Cache(cacheDirectory, cacheSize);
            builder.cache(cache);
        }

        NavinfoMultiMapFileTileSource tileSource = NavinfoMultiMapFileTileSource.builder()
                .apiKey("4wTLZyXcQym31pxC_HGy7Q") // Put a proper API key
                .httpFactory(new OkHttpEngine.OkHttpFactory(builder))
                //.locale("en")
                .build();
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("token", "eyJhbGciOiJIUzI1NiJ9.eyJjbGllbnRJZCI6MTAzLCJ1c2VyTmFtZSI6ImFkbWluIiwidXNlcklkIjoxLCJ1c2VyR3JvdXAiOiLnoJTlj5Hpg6giLCJvcmdJZCI6MSwiaWF0IjoxNjMwOTk4MzI5LCJleHAiOjE2MzEwODQ3Mjl9.0wFm8mAA9dCC2FmZj-u1dhxTFDRYx8AqVnh2C88hitk");
        tileSource.setHttpRequestHeaders(headerMap);
        VectorTileLayer l = new VectorTileLayer(this.vtmMap, tileSource);
        return l;
    }

    public void addLayer(String tag, Layer layer) {
        if (!layersMap.containsKey(tag)) {
            layersMap.put(tag, layer);
            vtmMap.layers().add(layer);
        }
    }


    public void addLayer(String tag, Layer layer, int group) {
        if (!layersMap.containsKey(tag)) {
            layersMap.put(tag, layer);
            vtmMap.layers().add(layer, group);
        }
    }

    public void addLayer(int index, String tag, Layer layer) {
        if (!layersMap.containsKey(tag)) {
            layersMap.put(tag, layer);
            vtmMap.layers().add(index, layer);
        }
    }

    public boolean containsLayer(String tag) {
        return layersMap.containsKey(tag);
    }

    public Layer getLayer(String tag) {
        return layersMap.get(tag);
    }

    public void removeLayer(String tag) {
        if (layersMap.containsKey(tag)) {
            Layer layer = layersMap.remove(tag);
            vtmMap.layers().remove(layer);
        }
    }

    /**
     * 返回默认marker图层
     *
     * @return mDefaultMarkerLayer
     */
    public ItemizedLayer getDefaultMarkerLayer() {
        return mDefaultMarkerLayer;
    }

    /**
     * 返回定位图层
     *
     * @return mLocationLayer
     */
    public LocationLayer getLocationLayer() {
        return mLocationLayer;
    }

//    /**
//     * 返回绘线图层
//     *
//     * @return mDefaultLineLayer
//     */
//    public PathLayer getDefaultLineLayer() {
//        return mDefaultLineLayer;
//    }

    @Override
    public boolean onItemSingleTapUp(int index, Object item) {
        return false;
    }

    @Override
    public boolean onItemLongPress(int index, Object item) {
        return false;
    }
}
